package com.dongdongshop.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.dongdongshop.core.Result;
import com.dongdongshop.core.ResultEnum;
import com.dongdongshop.pojo.user.TbUser;
import com.dongdongshop.pojo.vo.Comment;
import com.dongdongshop.pojo.vo.FileUploadVo;
import com.dongdongshop.service.commen.CommentService;
import com.dongdongshop.service.order.OrderService;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@CrossOrigin
@Controller
@RequestMapping("commentController")
public class CommentController {

    private final Logger logger = LoggerFactory.getLogger(CommentController.class);

    @Reference
    private CommentService commentService;

    @Reference
    private OrderService orderService;

    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("imgUpload")
    @ResponseBody
    public Result upload(@RequestParam("file") MultipartFile file) { // 图片上传
        // Endpoint以北京为例，其它Region请按实际情况填写。
        String endpoint = "oss-cn-beijing.aliyuncs.com";

        String accessKeyId = "LTAI4Fz9hj2Zq9GkwMPu6oXJ";
        String accessKeySecret = "gD3waD2kRBE0TYk6SypiN4bblk9srH";
        String bucketName = "dongdongshop-tyz";

        try {
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 上传文件流。
            InputStream inputStream = null;

            try {
                inputStream = file.getInputStream();//
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (ossClient.doesBucketExist(bucketName)) {
            } else {
                ossClient.createBucket(bucketName); //创建bucket 方法
            }

            //文件名
            String imageName = new Date().getTime() + "/" + file.getOriginalFilename();
            //第一个参数 ： bucket名字 第二个参数是我们要上传的文件的名字 ，第三个参数是文件的输入流

            ossClient.putObject(bucketName, imageName, inputStream);
            // ossClient.deleteObject(); 删除文件
//        ossClient.deleteObject(bucketName,imageName);
            //去阿里云上查询文件，需要访问bucketName ， 还需要文件名 ,第三个参数：文件访问的有效时间 从当前毫秒值开始计算
            URL url = ossClient.generatePresignedUrl(bucketName, imageName, new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 365));

            // 关闭OSSClient。
            ossClient.shutdown();
            FileUploadVo fileUploadVo = new FileUploadVo(imageName, url.toString());
            return Result.response(ResultEnum.SUCCESS).setData(fileUploadVo);
        }catch (Exception e){
            logger.error("图片上传：",e);
            return Result.response(ResultEnum.FAIL);
        }

    }

    @RequestMapping("insertComment")
    @ResponseBody
    public Result insertComment(Comment comment, String orderId){
        TbUser principal = (TbUser) SecurityUtils.getSubject().getPrincipal(); // 取出登录对象
        comment.setUserId(principal.getId());
        comment.setUserName(principal.getUsername());
        comment.setCommentTime(LocalDateTime.now());
        comment.setPid("0");
        comment.setIkedNum(0L);
        commentService.insertComment(comment);
        orderService.updateBuyerRate(Long.parseLong(orderId));
        return Result.response(ResultEnum.SUCCESS);
    }

    @RequestMapping("getComment")
    @ResponseBody
    public Result getComment(){
        List<Comment> comments = commentService.getComment();
        return Result.response(ResultEnum.SUCCESS).setData(comments);
    }

    @RequestMapping("incComment")
    @ResponseBody
    public Result incComment(String id, Long userId){
        Integer inc = 1;
        if (redisTemplate.hasKey(userId + ":" + id)){
            inc = -1;
            redisTemplate.delete(userId + ":" + id);
        }else {
            redisTemplate.boundValueOps(userId + ":" + id).set(1);
        }
        commentService.incComment(id,inc);
        return Result.response(ResultEnum.SUCCESS).setData(inc);
    }
}
